//
//  DrawView.m
//  CADisplayLink
//
//  Created by Justsoso on 16/4/7.
//  Copyright © 2016年 Justsoso. All rights reserved.
//

#import "DrawView.h"

@interface DrawView()
{
    CGFloat spiderY[50];
    CADisplayLink *link;
}
@property (nonatomic,strong) UIImage *spider;

@end
@implementation DrawView


- (void)setPlaying:(BOOL)playing
{
    _playing = playing;
    
    link.paused = !playing;
}

- (UIImage *)spider
{
    if (_spider == nil)
    {
        _spider = [UIImage imageNamed:@"spider"];
    }
    return _spider;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    int count = rect.size.width / self.spider.size.width;
    for (int i=0; i<count; i++)
    {
        spiderY[i] += arc4random_uniform(5);
        [self.spider drawAtPoint:CGPointMake(i*self.spider.size.width, spiderY[i])];
        
        if (spiderY[i] >= rect.size.height)
        {
            spiderY[i] = 0;
        }
    }
}

- (void)awakeFromNib
{
    if (link == nil)
    {
        link = [CADisplayLink displayLinkWithTarget:self selector:@selector(setNeedsDisplay)];
        [link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
        link.paused = YES;
    }
}

@end
